package com.honghe.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.honghe.constant.JwtClaimsConstant;
import com.honghe.context.BaseContext;
import com.honghe.properties.JwtProperties;
import com.honghe.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtDoctorInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long docId = Long.valueOf(claims.get(JwtClaimsConstant.DOC_ID).toString());
            BaseContext.setCurrentId(docId);
            return true;
        } catch (Exception e) {
            log.error("jwt校验失败:{}", e.getMessage());
            response.setStatus(401);
            /*Plan B
            Map<String,Object> map=new HashMap<>();
            map.put("code",2);
            map.put("msg","登录失败");
            map.put("data",null);
            JSONObject jsonObject=new JSONObject(map);
            String jsonString=jsonObject.toJSONString();
            response.getWriter().write(jsonString);*/
            return false;
        }
    }
}
